package com.bank;

import android.content.IntentFilter;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

import com.bank.GOME_M27A.M27SPDBbank;
import com.bank.lenovoz5.Z5SPDBbank;
import com.entity.BankOrder;
import com.entity.SMSCode;
import com.entity.User;
import com.receive.SMSReceiverSend;
import com.show.api.util.StringUtils;
import com.utils.ChatClient;
import com.utils.CodeUtils;
import com.utils.Constants;
import com.utils.FileHelper;
import com.utils.LogToFile;
import com.utils.UIUtils;
import com.utils.Util;

import org.junit.Test;
import org.junit.experimental.max.MaxCore;
import org.junit.runner.RunWith;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import static android.os.SystemClock.sleep;
import static com.utils.ChatClient.C_updateBalance_W;
import static com.utils.ChatClient.ConfirmOrder;
import static com.utils.ChatClient.PAUSE;
import static com.utils.ChatClient.S_paused_C;
import static com.utils.ChatClient.addWorkTime;
import static com.utils.ChatClient.getSerialNumber;
import static com.utils.ChatClient.getmap;
import static com.utils.ChatClient.list;
import static com.utils.ChatClient.mapDelete;
import static com.utils.ChatClient.requestSMSCode;
import static com.utils.ChatClient.setDevicesLog;
import static com.utils.ChatClient.userInfo;

/**
 * 项目名称：yzf
 * 类描述： 浦发银行自动脚本
 * 创建人：Administrator
 * 创建时间：2019/3/14 16:47
 * 修改人：Administrator
 * 修改时间：2019/3/14 16:47
 * 修改备注：
 */
@RunWith(AndroidJUnit4.class)
public class SPDBbank extends Bank {
    private int[][] xy_bank_no_s5 = new int[][]{{540, 1940},
            {180, 1440}, {540, 1440}, {890, 1440},
            {180, 1605}, {540, 1605}, {890, 1605},
            {180, 1770}, {540, 1770}, {890, 1770}};
    private int[][] xy_money_z5 = new int[][]{{440, 2010},
            {142, 1520}, {410, 1520}, {660, 1520},
            {142, 1690}, {410, 1690}, {660, 1690},
            {142, 1850}, {410, 1850}, {660, 1850}};
    private int[][] xy_money_s5 = new int[][]{{440, 1940},
            {142, 1440}, {410, 1440}, {660, 1440},
            {142, 1605}, {410, 1605}, {660, 1605},
            {142, 1770}, {410, 1770}, {660, 1770}};
    private int[][] xy_bank_no_z5 = new int[][]{{540, 2000},
            {185, 1530}, {540, 1530}, {890, 1530},
            {185, 1700}, {540, 1700}, {890, 1700},
            {185, 1855}, {540, 1855}, {890, 1855}};
    private List<String> errorCanncelContent = new ArrayList<>();
    public int[][] xy_bank_no;
    public int[][] xy_money;
    private User user;
    private String orderBankName;
    private String balance;
    private int smsFlag = 1;

    static {
        BANK_FLAG = "SPDB";
        BANK_NAME = "浦发银行";
        carrier = android.os.Build.MODEL;//机型
        Constants.MOBILE_BOB = "95528";
        Constants.MOBILE_BOB_86 = "+8695528";
        smsCode = "95528";
        context = InstrumentationRegistry.getTargetContext();
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
        ratio = screenWidth / 720f;
        ratioH = screenHeight / 1080f;
        Constants.CODE = "";
    }

    @Override
    public void keyPhone(int screenHeight) {

    }

    //键盘适配
    @Override
    public void keyPhone(String device) {
        switch (device) {
            case "Lenovo K520":
            case "Lenovo L38041":
                xy_bank_no = xy_bank_no_s5;
                xy_money = xy_money_s5;
                break;
            case "Lenovo L58041":
            case "Lenovo L78011":
                xy_bank_no = xy_bank_no_z5;
                xy_money = xy_money_z5;
                break;
        }
    }

    @Test
    public void start() throws UiObjectNotFoundException {
        LogToFile.init(InstrumentationRegistry.getTargetContext(), Constants.PROT);
        mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
        if (!carrier.contains("2017M27A")) {
            UIUtils.initServicePermission(mDevice);
        }
        mDevice.pressHome();
        mDevice.pressHome();
        showMsg("设备宽度==" + screenWidth + ",设备高度==" + screenHeight);
        Constants.getsTheModelAndVersionNumberAndVersionName(context, "浦发银行");
        keyPhone(carrier);
        if (carrier.contains("Lenovo L78011") || android.os.Build.MODEL.contains("Lenovo L38041")|| android.os.Build.MODEL.contains("Lenovo L58041")) {
            showMsg("进入Z5");
            new Z5SPDBbank(this);
        } else if (carrier.contains("2017M27A")) {
            showMsg("进入M27");
            new M27SPDBbank(this);
        }

        UiObject x = mDevice.findObject(new UiSelector().text("浦发银行"));
        x.click();

        SMSReceiverSend sMSReceiverSend = new SMSReceiverSend();
        Constants.CODE = "";
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.SMS_ACTION);
        filter.addAction("net.blogjava.mobile.SMSto");
        // 设置优先级 不然监听不到短信
        filter.setPriority(1000);
        context.registerReceiver(sMSReceiverSend, filter);
        ChatClient.start();
        transfer();
    }

    /**
     * 关闭广告及点击我的账户
     */
    private void transfer() throws UiObjectNotFoundException {
        sleep(ChatClient.overtime_10);
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime = System.currentTimeMillis();
            if (nowTime - ChatClient.begintime > ChatClient.overtime_15) {
                showMsg("关闭警告弹窗结束");
                break;
            }
            sleep(ChatClient.overtime_1);
            UiObject adPage = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/iv_advpage"));
            UiObject mTV_dialog_title = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/tv_dialog_title"));
            UiObject mBT_adPage_close = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/iv_closePage"));
            if (mTV_dialog_title.exists()) {
                if (mTV_dialog_title.getText().equals("提示")) {
                    UiObject mTV_dialog_close = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/btn_dialog_cancel"));
                    if (mTV_dialog_close.exists()) {
                        showMsg("关闭更新弹窗");
                        mTV_dialog_close.click();
                        sleep(ChatClient.overtime_1);
                    }
                }
            }
            if (adPage.exists() && mBT_adPage_close.exists()) {
                showMsg("关闭广告弹窗");
                mBT_adPage_close.click();
            }
            errorCanncelContent.add("本应用需要读取短信权限,请您允许或打开设置修改应用程序的权限。");
            errorCanncelContent.add("您的应用正在模拟器上运行，请注意操作安全！");
            errorCanncelContent.add("推荐您开通指纹登录，享受更快捷的登录体验!快来试试吧!");
            errorCanncelContent.add("您的手机已经ROOT，请注意手机操作安全！");

            UiObject errorMsgContent1;
            UiObject errorMsgContent2;
            UiObject canncelBtn;
            errorMsgContent1 = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/message"));
            if (errorMsgContent1.exists()) {
                showMsg("errorAlert 捕获到警告信息页面" + errorMsgContent1.getText());
                if (errorCanncelContent.contains(errorMsgContent1.getText())) {
                    canncelBtn = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank" +
                            ".per:id/negativeButton"));
                    showMsg("点掉警告弹窗");
                    canncelBtn.click();
                }
            }
            errorMsgContent2 = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/tv_dialog_message"));
            if (errorMsgContent2.exists()) {
                showMsg("errorAlert 捕获到警告信息页面" + errorMsgContent2.getText());
                if (errorCanncelContent.contains(errorMsgContent2.getText())) {
                    canncelBtn = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank" +
                            ".per:id/btn_dialog_cancel"));
                    showMsg("点掉警告弹窗");
                    canncelBtn.click();
                }
            }
        }
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime) {
                ChatClient.timer(LogToFile.getMethodName(), "首页《转账汇款》超时");
                return;
            }
            UiObject mTV_myAccount = mDevice.findObject(new UiSelector().className("android.widget.TextView").text("转账汇款"));

            if (mTV_myAccount.exists()) {
                showMsg("点击---转账汇款");
                mTV_myAccount.click();
                break;
            }
        }

        while (true) {
            //获取账号信息
            if (StringUtils.isEmpty(userInfo)) {
                ChatClient.msg("<YZF>{'header':'" + ChatClient.M_GET_BANK_LOGIN_INFO_P + "'}</YZF>");
                sleep(ChatClient.overtime_3);
            } else {
                user = new User();
                String[] res = userInfo.split(" ");
                user.setUserName(res[0]);
                user.setPwd(res[1]);
                user.setBankpwd(res[2]);
                user.setUseType(res[4]);
                user.setBankId(res[5]);
                break;
            }
        }
        login();
    }

    /**
     * 用户账号密码登录
     */
    private void login() throws UiObjectNotFoundException {
        sleep(ChatClient.overtime_3);
        showMsg("进入---登录页面");
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime) {
                ChatClient.timer(LogToFile.getMethodName(), ChatClient.loginError);
                return;
            }
//            UiObject mET_userUnmber = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/rl_layout_login_container"));
            UiObject mET_userPwd = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/et_login_user_pwd"));
//            if (mET_userUnmber.exists()) {
//                showMsg("填入账号");
//                mET_userUnmber.setText(user.getUserName());
//            }
            if (mET_userPwd.exists()) {
                showMsg("输入密码");
                mET_userPwd.click();
                clickKey(user.getPwd());
                break;
            }
        }

        while (true) {
            UiObject mBT_login = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/btn_login_new_login")
                    .text("登录"));
            if (mBT_login.exists()) {
                showMsg("点击登录按钮");
                mBT_login.click();
                sleep(ChatClient.overtime_3);
                break;
            }
        }

        while (true) {
            UiObject mBT_ = mDevice.findObject(new UiSelector().className("android.view.View").text("银行账号转账"));
            if (mBT_.exists()) {
                ChatClient.loginS();
                mBT_.click();
                break;
            }
        }
        accountPage();
    }

    /**
     * 账户总览页面
     */
    private void accountPage() {
        try {
            //            joinDetailsPage();
            while (true) {
                sleep(ChatClient.overtime_1);
                if (ChatClient.existOrder()) {
                    if (ConfirmOrder) {
                        showMsg("进入查账");
                        auditOrder();
                    } else {
                        showMsg("进行转账");
                        joinEditOrderPage();
                        remittanceBusiness();
                    }
                } else {
                    if (PAUSE) {
                        showMsg("等待订单");
                        joinEditOrderPage();
                        updateBalance(true);
                        waitOrder();
                    } else {
                        S_paused_C();
                        sleep(ChatClient.overtime_1);
                    }
                }
            }
        } catch (Exception e) {
            setDevicesLog(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 等待订单
     */
    private void waitOrder() throws UiObjectNotFoundException {
        //        joinEditOrderPage();
        if (ChatClient.waitExistOrder(ChatClient.overtime_60)) {
            showMsg("进行转账");
            remittanceBusiness();
        } else {
            backOrderListPage();
        }
    }

    /**
     * 进入订单页
     *
     * @throws UiObjectNotFoundException
     */
    private void joinEditOrderPage() throws UiObjectNotFoundException {
        while (true) {
            UiObject mBT = mDevice.findObject(new UiSelector().text("户名").className("android.view.View"));
            if (!mBT.exists()) {
                mBT = mDevice.findObject(new UiSelector().descriptionContains("户名").className("android.view.View"));
            }
            if (mBT.exists()) {
                showMsg("进入转账信息页");
                sleep(ChatClient.overtime_1);
                break;
            } else {
                UiObject mV = mDevice.findObject(new UiSelector().text("手机号转账").className("android.view.View"));
                if (mV.exists()) {
                    UiObject mV1 = mDevice.findObject(new UiSelector().text("银行账号转账").className("android.view.View"));
                    if (mV1.exists()) {
                        showMsg("进入转账信息页");
                        mV1.click();
                        sleep(ChatClient.overtime_5);
                    }
                }
            }
        }
    }

    /**
     * 上报余额
     *
     * @param isSave 保存本地
     * @throws UiObjectNotFoundException
     */
    private void updateBalance(boolean isSave) throws UiObjectNotFoundException {
        while (true) {
            UiObject mV = mDevice.findObject(new UiSelector().text("付款卡").className("android.view.View"));
            if (mV.exists()) {
                UiObject mV_money = mV.getFromParent(new UiSelector().index(2).className("android.view.View"));
                UiObject moneyChild = mV_money.getChild(new UiSelector().index(1).className("android.view.View"));
                if (moneyChild.exists()) {
                    String money = moneyChild.getText();
                    if (!StringUtils.isEmpty(money)) {
                        money = Util.replaceMoney(money);
                        balance = money.replaceAll(",", "");
                        if (!StringUtils.isEmpty(balance)) {
                            showMsg("余额---" + balance);
                            C_updateBalance_W(balance);
                            if (isSave) {
                                showMsg("本地保存余额");
                                String sumMoneyFile = user.getUserName() + BANK_FLAG + "_sumMoney.txt";
                                FileHelper.saveMoneySDFile(false, balance, sumMoneyFile);
                            }
                            break;
                        }
                    }
                }
            }
        }
    }


    /**
     * 查账业务
     */
    private void auditOrder() throws UiObjectNotFoundException {
        BankOrder bankOrder = list.get(0);
        updateBalance(false);
        backOrderListPage();
        addWorkTime(ChatClient.overtime_60);
        while (true) {
            UiObject mV_transferRecord = mDevice.findObject(new UiSelector().text("转账记录").className("android.view.View"));
            if (mV_transferRecord.exists()) {
                showMsg("点击进入转账记录");
                mV_transferRecord.click();
                break;
            }
        }
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_15) {
                showMsg("《无交易明细》超时");
                break;
            }
            UiObject mV_wujilu = mDevice.findObject(new UiSelector().resourceId("wujilu"));
            if (mV_wujilu.exists()) {
                reportCheckOrderStatus("近期无交易明细", Constants.STATE_PROCESS);
                return;
            }
        }

        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_15) {
                showMsg("未找到同名条目");
                balanceJudgment();
                sleep(ChatClient.overtime_2);
                backOrderListPage();
                return;
            }
            UiObject mRL_transactionTitle = mDevice.findObject(new UiSelector().text("本月").className("android.view.View"));
            if (mRL_transactionTitle.exists()) {
                UiObject mLV_item = mRL_transactionTitle.getFromParent(new UiSelector().className("android.view.View").index(1));
                if (mLV_item.exists()) {
                    UiObject mLV_item1 = mLV_item.getChild(new UiSelector().className("android.view.View").index(1));
                    if (mLV_item1.exists()) {
                        UiObject mV_name = mLV_item1.getChild(new UiSelector().index(0).className("android.view.View"));
                        if (mV_name.exists()) {
                            String name = mV_name.getText();
                            if (!StringUtils.isEmpty(name)) {
                                name = name.replaceAll(" ", "");
                                if (name.equals(bankOrder.getUserName())) {
                                    showMsg("进入账单详情...");
                                    mV_name.click();
                                    sleep(ChatClient.overtime_2);
                                    break;
                                } else {
                                    balanceJudgment();
                                    sleep(ChatClient.overtime_2);
                                    backOrderListPage();
                                    return;
                                }
                            }
                        }
                    }
                }
            }
        }
        String money = "", bankNo = "", name = "", businessStatus = "";
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_20) {
                showMsg("未进入账单详情");
                balanceJudgment();
                sleep(ChatClient.overtime_2);
                backOrderListPage();
                return;
            }
            UiObject mV = mDevice.findObject(new UiSelector().resourceId("detailHead"));
            UiObject mV1 = mDevice.findObject(new UiSelector().resourceId("pageE"));
            if (mV.exists() && mV1.exists()) {
                UiObject mV_name = mV.getChild(new UiSelector().resourceId("receive-name"));
                UiObject mV_bankNo = mV.getChild(new UiSelector().resourceId("receive-account"));
                UiObject mV_money = mV1.getChild(new UiSelector().resourceId("TranAmtE"));
                UiObject mV_status = mV1.getChild(new UiSelector().resourceId("TranStatusE"));
                if (mV_name.exists()) {
                    name = mV_name.getText().trim();
                }
                if (mV_bankNo.exists()) {
                    bankNo = mV_bankNo.getText().trim();
                }
                if (mV_money.exists()) {
                    money = mV_money.getText().trim();
                }
                if (mV_status.exists()) {
                    businessStatus = mV_status.getText().trim();
                }
                if (!StringUtils.isEmpty(bankNo)) {
                    bankNo = bankNo.replaceAll(" ", "");
                }
                if (!StringUtils.isEmpty(money)) {
                    money = Util.replaceMoney(money);
                    money = money.replaceAll("-", "");
                    money = money.replaceAll(",", "");
                }
                showMsg("账单信息：money=" + (Double.parseDouble(money) == Double.parseDouble(bankOrder.getMoney())) + ",bankNo=" + bankNo.equals(bankOrder
                        .getBankNo()) + ",name=" + name.equals(bankOrder.getUserName()) + ",businessStatus=" + businessStatus);
                if (Double.parseDouble(money) == Double.parseDouble(bankOrder.getMoney()) && bankNo.equals(bankOrder.getBankNo())
                        && name.equals(bankOrder.getUserName()) && !businessStatus.equals("交易失败")) {
                    reportCheckOrderStatus(businessStatus, Constants.STATE_SUCCESS);
                } else {
                    balanceJudgment();
                }
                break;
            }
        }
        sleep(ChatClient.overtime_2);
        backOrderListPage();
    }

    /**
     * 使用余额判断转账结果
     */
    private void balanceJudgment() {
        String sumMoneyFile = user.getUserName() + BANK_FLAG + "_sumMoney.txt";
        String oldMoney = FileHelper.readSDFile(sumMoneyFile);
        switch (Constants.changeInAmount(BANK_NAME, oldMoney, balance, list.get(0).getMoney())) {
            case "0":
                reportCheckOrderStatus("交易成功", Constants.STATE_SUCCESS);
                break;
            case "1":
                reportCheckOrderStatus("交易待处理...", Constants.STATE_FAIL);
                break;
            case "4":
                reportCheckOrderStatus("未查到条目", Constants.STATE_PROCESS);
                break;
        }
    }

    /**
     * 转账汇款业务
     */
    private void remittanceBusiness() throws UiObjectNotFoundException {
        BankOrder bankOrder = list.get(0);
        orderBankName = Constants.getBank(bankOrder.getBankName(), "SPDB");
        Constants.CODE = "";
        while (true) {
            UiObject mTV_bank = mDevice.findObject(new UiSelector().className("android.view.View").text("付款卡"));
            if (mTV_bank.exists()) {
                updateBalance(true);
                //                joinEditOrderPage();
            }
            UiObject mET_remittanceUser = mDevice.findObject(new UiSelector().text("户名").className("android.view.View"));
            if (mET_remittanceUser.exists()) {
                UiObject mET_remittanceUserName = mET_remittanceUser.getFromParent(new UiSelector().index(2).className("android.widget.EditText"));
                showMsg("填入收款户名");
                mET_remittanceUserName.setText(bankOrder.getUserName());
                break;
            }
        }

        while (true) {
            showMsg("输入收款账户");
            UiObject mET_bankNo = mDevice.findObject(new UiSelector().resourceId("pyAcctNoInput").index(2));
            if (mET_bankNo.exists()) {
                mET_bankNo.click();
                sleep(ChatClient.overtime_3);
                while (true) {
                    UiObject mBT_keys_close = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/digitpadedittext"));
                    if (mBT_keys_close.exists()) {
                        showMsg("弹出键盘...");
                        clickNumKey(xy_bank_no, bankOrder.getBankNo());
                        break;
                    } else {
                        showMsg("未弹出键盘...");
                        mET_bankNo.click();
                        sleep(ChatClient.overtime_1);
                    }
                }
                showMsg("输入结束...");
                break;
            }
        }

        while (true) {
            UiObject mBT_keys_close = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/digitkeypad_ok").text
                    ("确定"));
            if (mBT_keys_close.exists()) {
                showMsg("收起键盘");
                mBT_keys_close.click();
                sleep(ChatClient.overtime_1);
                break;
            }
        }
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_5) {
                showMsg("选择银行名超时...");
                break;
            }
            UiObject mTV_bankNameSelect = null;
            if (screenHeight == 2016) {
                mTV_bankNameSelect = mDevice.findObject(new UiSelector().text("请选择收款开户行"));
            }
            if (mTV_bankNameSelect != null && mTV_bankNameSelect.exists()) {
                showMsg("选择收款银行");
                mTV_bankNameSelect.click();
                sleep(ChatClient.overtime_3);
                if (selectBank()) {
                    break;
                } else {
                    return;
                }
            }
        }
        while (true) {
            UiObject mET_setAmount = mDevice.findObject(new UiSelector().resourceId("money"));
            if (mET_setAmount.exists()) {
                showMsg("点击汇款金额");
                mET_setAmount.click();
                sleep(ChatClient.overtime_2);
                putMoney();
                break;
            }
        }

        while (true) {
            UiObject mBT = null;
            mBT = mDevice.findObject(new UiSelector().className("android.widget.Button").descriptionContains("确认转账"));
            if (!mBT.exists()) {
                mBT = mDevice.findObject(new UiSelector().className("android.widget.Button").text("确认转账"));
            }
            if (mBT != null && mBT.exists()) {
                showMsg("点击确认转账");
                mBT.click();
                sleep(ChatClient.overtime_5);
                break;
            }
        }
        /*
         * 处理账单错误
         */
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_8) {
                showMsg("账单错误超时");
                break;
            }
            String errorMsg = errorMsg();
            if (!StringUtils.isEmpty(errorMsg)) {
                ChatClient.msg("<YZF>{'header':'" + ChatClient.M_TRANSFERFINISH_P + "'}</YZF>");
                reportTransferOrderStatus(errorMsg, Constants.STATE_FAIL);
                backOrderListPage();
                return;
            }
        }
        /*
         * 处理短信与转账密码
         */
        smsFlag = 1;
        SMSOrPwd();
        /*
         * 结果页处理
         */
        ChatClient.msg("<YZF>{'header':'" + ChatClient.M_TRANSFERFINISH_P + "'}</YZF>");
        orderFinish();
    }

    /**
     * 输入金额并判定金额
     *
     * @throws UiObjectNotFoundException
     */
    private void putMoney() throws UiObjectNotFoundException {
        String money = list.get(0).getMoney();
        clickNumKey(xy_money, money);
        mDevice.click(800, 960);

        sleep(ChatClient.overtime_2);
        String moneyText;
        while (true) {
            UiObject mET_setAmount = mDevice.findObject(new UiSelector().resourceId("money"));
            if (mET_setAmount.exists()) {
                showMsg("获取输入金额");
                String text = mET_setAmount.getText().trim();
                moneyText = text.replaceAll(",", "");
                if (Double.parseDouble(moneyText) == Double.parseDouble(money)) {
                    showMsg("输入金额成功");
                    break;
                } else {
                    showMsg("输入金额错误");
                    mET_setAmount.click();
                    sleep(ChatClient.overtime_2);
                    for (int i = 0; i < moneyText.length() + 3; i++) {
                        showMsg("删除金额");
                        mDevice.click(940, 1475);
                        sleep(ChatClient.overtime_1);
                    }
                    putMoney();
                    break;
                }
            }
        }
    }


    /**
     * 短信与转账密码处理
     */
    private void SMSOrPwd() throws UiObjectNotFoundException {
        addWorkTime(ChatClient.overtime_60);
        while (true) {
            UiObject mV_dialog_title = mDevice.findObject(new UiSelector().text("请输入密码").className("android.view.View"));
            if (mV_dialog_title.exists()) {
                showMsg("进入验证码，密码输入页");
                break;
            }
        }

        while (true) {
            UiObject mV_pwd = mDevice.findObject(new UiSelector().text("请输入6位交易密码").className("android.view.View"));
            if (mV_pwd.exists()) {
                UiObject mV_pwd_input = mV_pwd.getFromParent(new UiSelector().index(2).className("android.view.View"));
                if (mV_pwd_input.exists()) {
                    showMsg("准备输入交易密码...");
                    mV_pwd_input.click();
                    sleep(ChatClient.overtime_2);
                    clickKey(user.getBankpwd());
                    sleep(ChatClient.overtime_2);
                    break;
                }
            }
        }

        while (true) {
            UiObject mET_dialog_pwd = mDevice.findObject(new UiSelector().resourceId("pwd").text("请输入动态密码"));
            if (mET_dialog_pwd.exists()) {
                showMsg("点击弹出短信密码键盘");
                mET_dialog_pwd.click();
                sleep(ChatClient.overtime_2);
                break;
            }
        }

        if (user.getUseType().equals("1")) {
            showMsg("处理转账短信---真机");
            //等待验证码确认页面
            boolean isNext = getMsgByPhone();
            if (isNext) {
                setPhoneSMS();
            } else {
                showMsg("关闭短信键盘");
                mDevice.click(180, 1980);
            }
        } else {
            showMsg("处理转账短信---无SIM卡");
            boolean isNext = setNotSIM_SMS();
            if (!isNext) {
                showMsg("关闭短信键盘");
                mDevice.click(180, 1980);
            }
        }

        while (true) {
            UiObject mDialog_text = mDevice.findObject(new UiSelector().text("请输入6位交易密码").className("android.view.View"));
            if (mDialog_text.exists()) {
                UiObject mDialog_button = mDialog_text.getFromParent(new UiSelector().text("确认转账").className("android.widget.Button"));
                if (mDialog_button.exists()) {
                    showMsg("点击确认转账");
                    int x = mDialog_button.getVisibleBounds().centerX();
                    int y = mDialog_button.getVisibleBounds().centerY();
                    mDevice.click(x, y);
                    mDevice.click(x, y);
                    sleep(ChatClient.overtime_5);
                    break;
                }
            }
        }
        //mDevice.click(180, 2000);
        sleep(ChatClient.overtime_2);

        long begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - begintime > ChatClient.overtime_8) {
                showMsg("无弹窗");
                break;
            }
            UiObject mBT1 = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/dialog_close"));
            UiObject mBT2 = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/positiveButton").text("确定"));
            if (mBT1.exists()) {
                mBT1.click();
                sleep(ChatClient.overtime_1);
                againInpoutSMS();
                break;
            }
            if (mBT2.exists()) {
                mBT2.click();
                sleep(ChatClient.overtime_1);
                againInpoutSMS();
                break;
            }
        }
    }

    /**
     * 重新打开短信输入弹窗
     */
    private void againInpoutSMS() throws UiObjectNotFoundException {
        showMsg("验证码输入错误次数：" + smsFlag);
        if (smsFlag < 3) {
            while (true) {
                UiObject mBT = mDevice.findObject(new UiSelector().className("android.widget.Button").text("确认转账"));
                if (mBT != null && mBT.exists()) {
                    showMsg("点击确认转账");
                    mBT.click();
                    sleep(ChatClient.overtime_3);
                    smsFlag += 1;
                    break;
                }
            }
            SMSOrPwd();
        } else {
            ChatClient.timer(LogToFile.getMethodName(), "短信获取失败...");
            return;
        }
    }

    /**
     * 处理无SIM卡手机短信逻辑
     */
    private boolean setNotSIM_SMS() {
        ChatClient.smsCode = null;
        if (smsFlag > 1) {
            sleep(ChatClient.overtime_20);
        } else {
            sleep(ChatClient.overtime_2);
        }
        SMSCode smsCode = requestSMSCode(user.getUserName(), user.getBankId());
        if (!StringUtils.isEmpty(smsCode.getSmscode())) {
            clickNumKey(xy_bank_no, smsCode.getSmscode());
            return true;
        } else {
            showMsg("未收到验证码...");
            return false;
        }
    }

    /**
     * 监听短信点击输入验证码
     *
     * @throws UiObjectNotFoundException
     */
    private void setPhoneSMS() throws UiObjectNotFoundException {
        clickNumKey(xy_bank_no, Constants.CODE);//输入短信验证码
        sleep(ChatClient.overtime_1);
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_5) {
                showMsg("短信弹窗超时");
                break;
            }
            UiObject mDialog_button = mDevice.findObject(new UiSelector().text("确定").resourceId("cn.com.spdb.mobilebank" +
                    ".per:id/btn_dialog_positive"));
            if (mDialog_button.exists()) {
                showMsg("关闭短信弹窗");
                mDialog_button.click();
                sleep(ChatClient.overtime_2);
                break;
            }
        }
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime1 = System.currentTimeMillis();
            if (nowTime1 - ChatClient.begintime > ChatClient.overtime_5) {
                showMsg("短信验证码框未显示");
                break;
            }
            UiObject mET_sms = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/transfer_dynamic"));
            if (mET_sms.exists()) {
                String sms_code = mET_sms.getText();
                if (!StringUtils.isEmpty(sms_code)) {
                    showMsg("点击短验证码输入栏---" + sms_code);
                    mET_sms.click();
                    sleep(ChatClient.overtime_2);
                    for (int i = 0; i <= sms_code.length(); i++) {
                        showMsg("删除回退短信密码");
                        if (screenHeight == 2102) {
                            mDevice.click(910, 2020);
                        } else {
                            mDevice.click(910, 1950);
                        }
                        sleep(500);
                    }
                }
            }
        }

        //        clickNumKey(Constants.CODE);
    }

    //真机短信验证码
    private boolean getMsgByPhone() {
        //判断是否获取到短信
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_45) {
                showMsg("未收到短信验证码");
                return false;
            }

            if (!StringUtils.isEmpty(Constants.CODE)) {
                LogToFile.d("====收到短信验证码流程===", ">>>>>获取短信验证码");
                sleep(1000);
                return true;
            }
        }
    }

    /**
     * 转账结果页
     */
    private void orderFinish() throws UiObjectNotFoundException {
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime = System.currentTimeMillis();
            if (nowTime - ChatClient.begintime > ChatClient.overtime_30) {
                ChatClient.timer(LogToFile.getMethodName(), "转账结果页超时");
                return;
            }
            UiObject titleTv = mDevice.findObject(new UiSelector().className("android.view.View").text("转账结果"));
            if (titleTv.exists()) {
                showMsg("进入转账结果页");
                break;
            }
            sleep(ChatClient.overtime_1);
        }

        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            long nowTime = System.currentTimeMillis();
            if (nowTime - ChatClient.begintime > ChatClient.overtime_8) {
                showMsg("转账失败页超时");
                break;
            }
            UiObject mFailPage = mDevice.findObject(new UiSelector().text("转账失败").className("android.view.View"));
            UiObject successPage = mDevice.findObject(new UiSelector().text("转账成功").className("android.view.View"));
            if (mFailPage.exists()) {
                showMsg("跳转转账失败界面");
                UiObject mV_msg = mFailPage.getFromParent(new UiSelector().className("android.view.View").index(3));
                if (mV_msg.exists()) {
                    String failInfo = mV_msg.getText();
                    failInfo = failInfo.replaceAll("\r|\n|\\s", "");
                    if (!StringUtils.isEmpty(failInfo)) {
                        showMsg("转账失败：" + failInfo);
                        reportTransferOrderStatus(failInfo, Constants.STATE_FAIL);
                        backOrderListPage();
                        return;
                    }
                }
            } else if (successPage.exists()) {
                showMsg("跳转转账成功界面");
                UiObject mV_msg = successPage.getFromParent(new UiSelector().className("android.view.View").index(3));
                if (mV_msg.exists()) {
                    String successInfo = mV_msg.getText();
                    successInfo = successInfo.replaceAll("\r|\n|\\s", "");
                    if (!StringUtils.isEmpty(successInfo)) {
                        int type = Constants.getStr(successInfo);
                        if (type == 0) {
                            DecimalFormat formater = new DecimalFormat("#0.##");
                            balance = formater.format(Double.parseDouble(balance) - Double.parseDouble(list.get(0).getMoney()));
                            showMsg("本地保存余额");
                            String sumMoneyFile = user.getUserName() + BANK_FLAG + "_sumMoney.txt";
                            FileHelper.saveMoneySDFile(false, balance, sumMoneyFile);
                            reportTransferOrderStatus(successInfo, Constants.STATE_SUCCESS);
                            backOrderListPage();
                            return;
                        } else {
                            reportTransferOrderStatus(successInfo, Constants.STATE_FAIL);
                            backOrderListPage();
                            return;
                        }
                    }
                }
            }
        }
    }

    /**
     * 查账订单状态上报
     *
     * @param info  状态
     * @param state 成功与否
     */
    private void reportCheckOrderStatus(String info, int state) {
        showMsg("转账状态---" + info);
        String mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'浦发银行'," +
                "'info':'" + info + "'";
        String json = "'order':'" + list.get(0).getOrder() + "','balance':'" + balance + "','state':" + state + "," +
                "'type':1";
        showMsg("mobileD = " + mobileD);
        showMsg("json = " + json);
        ChatClient.msg("<YZF>{'header':'" + ChatClient.S_CONFIRM_TRADE_RESULT_C + "'," + json + "," + mobileD +
                "}</YZF>");
        mapDelete(list.get(0).getOrder());
        getmap();
    }

    /**
     * 转账订单状态上报
     *
     * @param info  状态
     * @param state 成功与否
     */
    private void reportTransferOrderStatus(String info, int state) {
        showMsg("转账状态---" + info);
        String mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "','phoneModel':'浦发银行'," +
                "'info':'" + info + "'";
        String json = "'order':'" + list.get(0).getOrder() + "','balance':'" + balance + "','state':" + state + "," +
                "'type':1";
        showMsg("mobileD = " + mobileD);
        showMsg("json = " + json);
        ChatClient.msg("<YZF>{'header':'" + ChatClient.M_SEND_TRADE_RESULT_P + "'," + json + "," + mobileD + "}</YZF>");
        mapDelete(list.get(0).getOrder());
        getmap();
    }

    /**
     * 订单数据选择银行
     *
     * @throws UiObjectNotFoundException 异常捕获
     */
    private boolean selectBank() throws UiObjectNotFoundException {
        addWorkTime(ChatClient.overtime_60);
        ChatClient.begintime = System.currentTimeMillis();
        while (true) {
            UiObject mTV_bankTitle = mDevice.findObject(new UiSelector().className("android.view.View").text("选择收款银行"));
            if (mTV_bankTitle.exists()) {
                showMsg("进入银行选择页面");
                break;
            }
        }

        while (true) {
            UiObject mET_selectBank = mDevice.findObject(new UiSelector().className("android.widget.EditText").index(0));
            if (mET_selectBank.exists()) {
                showMsg("填入账单银行");
                mET_selectBank.setText(orderBankName);
                break;
            }
        }
        sleep(ChatClient.overtime_5);
        ChatClient.begintime = System.currentTimeMillis();//开始时间
        while (true) {
            long nowtime = System.currentTimeMillis();
            if ((nowtime - ChatClient.begintime) > ChatClient.overtime_10) {
                String mobileD = "'devices':'" + getSerialNumber() + "','prot':'" + Constants.PROT + "'," +
                        "'phoneModel':'浦发银行'," +
                        "'info':'银行名错误'";
                String json = "'order':'" + list.get(0).getOrder() + "','balance':'" + balance + "','state':1," +
                        "'type':1";
                ChatClient.msg("<YZF>{'header':'" + ChatClient.M_SEND_TRADE_RESULT_P + "'," + json + "," + mobileD +
                        "}</YZF>");
                //删除处理过的订单
                mapDelete(list.get(0).getOrder());
                getmap();
                sleep(ChatClient.overtime_2);
                backOrderListPage();
                return false;
            }
            showMsg("搜索---" + orderBankName);
            UiObject mTV_bankItem = mDevice.findObject(new UiSelector().text(orderBankName).index(1));
            if (mTV_bankItem != null && mTV_bankItem.exists()) {
                showMsg("点击---" + orderBankName);
                mTV_bankItem.click();
                sleep(ChatClient.overtime_3);
                break;
            }
            sleep(ChatClient.overtime_1);
        }
        return true;
    }

    /**
     * 返回上页从新进入刷新错误账单页面
     *
     * @throws UiObjectNotFoundException
     */
    private void backOrderListPage() {
        while (true) {
            UiObject mBT = mDevice.findObject(new UiSelector().text("手机号转账").className("android.view.View"));
            if (!mBT.exists()) {
                mBT = mDevice.findObject(new UiSelector().descriptionContains("手机号转账").className("android.view.View"));
            }
            if (mBT.exists()) {
                showMsg("返回《转账汇款》主页");
                break;
            } else {
                mDevice.pressBack();
                sleep(ChatClient.overtime_5);
            }
        }
    }

    /**
     * 点击密码
     *
     * @param pwd 密码
     * @throws UiObjectNotFoundException 异常捕获
     */
    private void clickKey(String pwd) throws UiObjectNotFoundException {
        char[] cs = pwd.toCharArray();
        for (char i : cs) {
            long startTime = System.currentTimeMillis();
            while (true) {
                long nowTime = System.currentTimeMillis();
                if (nowTime - startTime > ChatClient.overtime_20) {
                    ChatClient.timer(LogToFile.getMethodName(), ChatClient.keyIdentificationErr);
                    return;
                }
                UiObject key = mDevice.findObject(new UiSelector().className("android.widget.Button").text(String.valueOf(i)));
                if (key.exists()) {
                    showLog("点击：*");
                    key.longClick();
                    break;
                }
            }
            sleep(ChatClient.overtime_1);
        }
    }

    /**
     * 点击收款账号
     *
     * @param bankNo 账号
     */
    private void clickNumKey(int[][] xy, String bankNo) {
        char[] array = bankNo.toCharArray();
        int j = 0;
        for (char c : array) {
            if (c == '.') {
                showMsg("点击--- .");
                if (screenHeight != 2102) {
                    mDevice.click(670, 1950);
                } else {
                    mDevice.click(185, 2020);
                }
            } else {
                int i = Integer.parseInt(String.valueOf(c));
                mDevice.click(xy[i][0], xy[i][1]);
                showMsg("点击---" + j);
                j++;
            }
            sleep(ChatClient.overtime_1);
        }
    }

    private String errorMsg() throws UiObjectNotFoundException {
        UiObject errorMsgTitle = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/title"));
        UiObject errorMsgContent;
        UiObject errorMsgBtn;
        String errorResult;
        if (errorMsgTitle.exists()) {
            errorMsgContent = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/message"));
            if (errorMsgContent.exists()) {
                errorResult = errorMsgContent.getText();
                showMsg("errorMsg  = " + errorResult);
                errorMsgBtn = mDevice.findObject(new UiSelector().resourceId("cn.com.spdb.mobilebank.per:id/positiveButton"));
                if (errorMsgBtn.exists()) {
                    showMsg("点击提示弹窗《确定》");
                    errorMsgBtn.click();
                    return errorResult;
                }
            }
        }
        return "";
    }

    public static void showLog(String msg) {
        Log.i("浦发银行", msg);
    }

    public static void showMsg(String msg) {
        LogToFile.showLog("浦发银行", msg);
    }
}
